import axios from "axios";
import router from "../router/index";
import { ElMessage } from "element-plus";

/**
 * 创建axios示例
 */
const ENV = process.env.NODE_ENV;
const host =
    ENV === "development" ? "http://localhost:3000" : "http://api.ITclass.top";

const service = axios.create({
    baseURL: host,
    timeout: "3000",
});

/**
 * 请求拦截器
 */
service.interceptors.request.use((config) => {
    if (config.url.indexOf("/register") < 0 && config.url.indexOf("/login") < 0) {
        config.headers.Authorization = localStorage.getItem("token");
    }
    return config;
});

/**
 * 响应拦截器
 */
service.interceptors.response.use(
    (res) => {
        const { code, message } = res.data;
        if (code === 200) {
            return res.data; // 返回完整的响应数据
        } else {
            ElMessage({
                message: message || "请求失败",
                type: "error",
            });
            if (message === "身份认证失败") {
                router.push("/login");
            }
            return Promise.reject(new Error(message));
        }
    },
    (error) => {
        ElMessage.error("网络错误，请稍后再试");
        return Promise.reject(error);
    }
);



/**
 * 封装请求
 */
const request = (options) => {
    if (options.method === "get") {
        options.params = options.data;
    }
    return service(options);
};

export default request;
